# -*- coding: utf-8 -*-
import hashlib
import json
from collections import OrderedDict

import requests
from django.conf import settings

from async import async_job
from common.order import db as order_db
from common.order.db import get_pay, add_pay_success
from common.order.model import PAY_STATUS
from common.utils import track_logging
from common.utils.exceptions import ParamError

_LOGGER = track_logging.getLogger(__name__)

APP_CONF = {
    'DZZFXYE': {
        'API_KEY': '8b2de685acc4efxye3f147eaded49bd',
        'gateway': 'http://pay02.xushihudong.com:9911/code/createOrder',
        'query_gateway': 'http:// pay02.xushihudong.com:9911/code/getPayOtherResult',
    },
}


def _get_api_key(mch_id):
    return APP_CONF[mch_id]['API_KEY']


def _get_gateway(mch_id):
    return APP_CONF[mch_id]['gateway']


def _get_query_gateway(mch_id):
    return APP_CONF[mch_id]['query_gateway']


# merno,cpparam,fee,orderno
def generate_order_sign(d, key):
    s = 'cpparam={}&fee={}&merno={}&orderno={}&key={}'.format(d['cpparam'], d['fee'], d['merno'], d['orderno'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


# merno,cpparam,fee,ffid,orderno
def generate_notify_sign(d, key):
    s = 'cpparam={}&fee={}&ffid={}&merno={}&orderno={}&key={}'.format(d['cpparam'], d['fee'], d['ffid'], d['merno'],
                                                                      d['orderno'], key)
    m = hashlib.md5()
    m.update(s.encode('utf8'))
    sign = m.hexdigest().upper()
    return sign


def verify_notify_sign(params, key):
    sign = params['sign']
    calculated_sign = generate_notify_sign(params, key)
    if sign != calculated_sign:
        _LOGGER.info("xunpay sign: %s, calculated sign: %s", sign, calculated_sign)
        raise ParamError('sign not pass, data: %s' % params)


# 支付类型.支付宝：01，微信：02，快捷：03，QQ钱包：04
def _get_pay_type(service):
    if service == 'wxpay':
        payType = '02'
    elif service == 'alipay':
        payType = '01'
    elif service == 'qq':
        payType = '04'
    else:
        payType = '03'
    return payType


def _get_device_ip(info):
    try:
        extra = json.loads(info['extra'])
    except:
        extra = {}
    user_info = extra.get('user_info', {})
    return user_info.get('device_ip') or '127.0.0.1'


def create_charge(pay, pay_amount, info):
    mch_id = info['app_id']
    service = info.get('service')
    key = _get_api_key(mch_id)
    parameter_dict = OrderedDict((
        ('merno', mch_id),
        ('orderno', str(pay.id)),
        ('paytype', _get_pay_type(service)),
        ('fee', str(int(pay_amount * 100))),
        ('ip', _get_device_ip(info)),
        ('cpparam', 'kkkkk'),
        ('callbackurl', '{}/pay/api/{}/xunpay/{}'.format(settings.NOTIFY_PREFIX, settings.RETURN_PATH, pay.id)),
        ('notifyurl', '{}/pay/api/{}/xunpay/{}'.format(settings.NOTIFY_PREFIX, settings.NOTIFY_PATH, mch_id)),
        ('app', 'charge'),
        ('goodsname', 'charge'),
    ))
    parameter_dict['sign'] = generate_order_sign(parameter_dict, key)
    _LOGGER.info("xunpay create data: %s", parameter_dict)
    headers = {'Content-Type': 'application/x-www-form-urlencoded'}
    response = requests.post(_get_gateway(mch_id), data=parameter_dict, headers=headers, timeout=3)
    _LOGGER.info("xunpay create rsp: %s", response.text)
    j = json.loads(response.text)
    order_db.fill_third_id(pay.id, j['orderid'])
    return {'charge_info': j['url']}


def check_notify_sign(request, app_id):
    key = _get_api_key(app_id)
    data = dict(request.GET.iteritems())
    _LOGGER.info("xunpay notify data: %s", data)
    verify_notify_sign(data, key)
    pay_id = data['orderno']
    if not pay_id:
        _LOGGER.error("fatal error, pay object not exists, data: %s" % data)
        raise ParamError('xunpay event does not contain valid pay ID')

    pay = get_pay(pay_id)
    if not pay:
        raise ParamError('pay_id: %s invalid' % pay_id)
    if pay.status != PAY_STATUS.READY:
        raise ParamError('pay %s has been processed' % pay_id)

    mch_id = pay.mch_id
    trade_status = int(data['status'])
    trade_no = data['ffid']
    total_fee = float(data['fee']) / 100.0

    extend = {
        'trade_status': trade_status,
        'trade_no': trade_no,
        'total_fee': total_fee
    }
    from common.channel.pay import check_channel_order
    check_channel_order(pay_id, total_fee, app_id)
    # 1为成功，6为退款，其他为失败
    if trade_status == 1:
        _LOGGER.info('xunpay check order success, user_id:%s pay_id:%s' % (mch_id, pay_id))
        add_pay_success(mch_id, pay_id, total_fee, trade_no, extend)
        # async notify
        async_job.notify_mch(pay_id)


def query_charge(pay_order, app_id):
    pass
    # pay_id = pay_order.id
    # p_dict = {
    #     'cpid': app_id,
    #     'mch_no': str(pay_order.third_id),
    # }
    # _LOGGER.info(u'xunpay query data: %s', p_dict)
    # response = requests.get(_get_query_gateway(app_id), data=p_dict,)
    # _LOGGER.info(u'xunpay query: %s', response.text)
    # data = json.loads(response.text)
    # if response.status_code == 200:
    #     trade_status = int(data['result'])  # 0 订单未成功 1订单成功
    #     total_fee = float(data['fee']) / 100.0
    #     trade_no = data['orderid']
    #     extend = {
    #         'trade_status': trade_status,
    #         'trade_no': trade_no,
    #         'total_fee': total_fee
    #     }
    #
    #     if trade_status == 1:
    #         _LOGGER.info('xunpay query order success, mch_id:%s pay_id:%s' % (pay_order.mch_id, pay_id))
    #         res = add_pay_success(pay_order.mch_id, pay_id, total_fee, trade_no, extend)
    #         if res:
    #             async_job.notify_mch(pay_order.id)
    # else:
    #     _LOGGER.warn('xunpay data error, status_code: %s', response.status_code)
